<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/7
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\Help;
use app\common\facade\TransItem;
use app\common\services\JobService;
use app\common\services\UserService;
use think\App;
use think\Db;
use think\Validate;

/**
 *
 * Class UserCenter
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/7
 */
class UserCenter extends ApiBase
{


    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userInfo()
    {
        $this->user = (new UserService())->userInfo(Arr::get($this->user, 'id'));

        if ($this->request->param('userExtend', false)) {
            $userExtend = Db::name('user_extend')
                ->where('user_id', $this->userId)
                ->find() ?: [];
            $userExtend['showMobile'] = Help::ignoreMobile(Arr::get($userExtend, 'mobile', ''));
            $userExtend['showIdCard'] = Help::ignoreIdCard(Arr::get($userExtend, 'id_card', ''));
            $userExtend['showGender'] = TransItem::transGender(Arr::get($userExtend, 'true_sex', 0));
            $userExtend['showProfession'] = TransItem::transProfession(Arr::get($userExtend, 'profession'));
            $userExtend['showEducation'] = TransItem::transEducation(Arr::get($userExtend, 'education_class', 0));
            $userExtend['showSchool'] = Db::name('school')->where('id', Arr::get($userExtend, 'education_school'))->value('name') ?: '';
            $userExtend['showMajor'] = Db::name('school_major')
                ->where('id', Arr::get($userExtend, 'education_major'))->value('name') ?: '';
            $this->user['extend'] = $userExtend;
        }

        if ($this->request->param('userGroup', false)) {
            $this->user['groupInfo'] = Db::name('user_group')
                ->where('id', Arr::get($this->user, 'group'))
                ->find() ?: [];
        }

        if ($this->request->param('userExtendBus', false)) {
            $userExtendBus = Db::name('user_extend_bus')
                ->where('user_id', $this->userId)
                ->find() ?: [];
            $this->user['extendBus'] = $userExtendBus;
        }


        $isShowUserInfo = (new UserService())->checkUserInfoIsDone($this->user);

        $this->response([
            'userInfo'          => $this->user,
            'isShowUserInfo'    => !$isShowUserInfo,
        ]);
    }




    /**
     * 用户收藏
     * @throws \think\Exception
     */
    public function collect()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        if ($id && $type) {
            $result = (new UserService())->userCollect($id, $this->userId, $type);
            if ($result) {
                $this->response();
            }
            $this->response(
                [],
                ApiConstant::USER_COLLECT_ERROR,
                ApiConstant::USER_COLLECT_ERROR_STR
                );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }

    /**
     * 用户取消收藏
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delCollect()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        if ($id && $type) {
            $result = (new UserService())->userDelCollect($id, $this->userId, $type);
            if ($result) {
                $this->response([
                    'id'    => $id,
                    'type'  => $type
                ]);
            }
            $this->response(
                [],
                ApiConstant::USER_COLLECT_ERROR,
                ApiConstant::USER_COLLECT_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 个人认证需要的界面数据
     */
    public function approvePersonNeed()
    {
        $this->response([
            'educationList'     => TransItem::transEducation(),
            'professionList'    => TransItem::transProfession(),
        ]);
    }


    /**
     * 用户申请实名认证成  个人用户
     */
    public function submitApprovePerson()
    {
        $postData = $this->request->post();
        $validate = new Validate(
            [
               /* 'id_card'           => 'require|max:18|min:18',*/
                'true_name'         => 'require',
                'mobile'            => 'require',
                'profession'        => 'require',
                /*'id_card_zm_img'    => 'require',
                'id_card_bm_img'    => 'require',*/
                'provinceid'        => 'require',
                'cityid'            => 'require',
                'areaid'            => 'require',
                'smsCode'           => 'require',
            ],
            [
                /*'id_card.require'           => '身份证号码必填！',*/
                'true_name.require'         => '真实姓名不能为空！',
                'mobile.require'            => '联系方式不能为空！',
                'profession.require'        => '职业不能为空！',
               /* 'id_card_zm_img.require'    => '请上传身份证!',
                'id_card_bm_img.require'    => '请上传身份证!',*/
                'provinceid.require'        => '请选择所属地区!',
                'cityid.require'            => '请选择所属地区!',
                'areaid.require'            => '请选择所属地区!',
                'smsCode.require'           => '请填写验证码',
            ]
        );
        if ($validate->check($postData)) {
            $postData['user_id'] = $this->userId;
            $postData['type'] = 1;
            try {
                $this->__checkApproveSmsCode($postData);
                //地区转换
                $provincesId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'provinceid')) . '%')
                    ->where('area_deep', 1)
                    ->value('area_id') ?: 0;
                $cityId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'cityid')) . '%')
                    ->where('area_deep', 2)
                    ->where('area_parent_id', $provincesId)
                    ->value('area_id') ?: 0;
                $areaId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'areaid')) . '%')
                    ->where('area_deep', 3)
                    ->where('area_parent_id', $cityId)
                    ->value('area_id') ?: 0;
                $postData['provinceid'] = $provincesId;
                $postData['cityid'] = $cityId;
                $postData['areaid'] = $areaId;

                $result = (new UserService())->submitApprovePerson($postData);
                if ($result) {
                    $this->response();
                }
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    ApiConstant::API_ERROR_STR
                );
            } catch (\Exception $e){
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_ERROR,
            $validate->getError()
        );
    }


    /**
     * 用户认证成企业
     */
    public function submitApproveCompany()
    {
        $postData = $this->request->post();
        $validate = new Validate(
            [
                'company_name'          => 'require',
                'legal_person_name'     => 'require',
                'legal_person_id_card'  => 'require',
                'company_mobile'        => 'require',
                'company_license'       => 'require',
                'company_license_img'   => 'require',
                'id_card_zm_img'        => 'require',
                'id_card_bm_img'        => 'require',
                'provinceid'            => 'require',
                'smsCode'               => 'require',
            ],
            [
                'company_name.require'              => '公司名称不能为空！',
                'company_mobile.require'            => '公司联系方式不能为空！',
                'legal_person_name.require'         => '法人姓名不能为空！',
                'legal_person_id_card.require'      => '法人证件号不能为空！',
                'company_license.require'           => '营业执照号不能为空！',
                'company_license_img.require'       => '请上传营业执照!',
                'id_card_zm_img.require'            => '请上传身份证!',
                'provinceid.require'                => '请选择所属地区!',
                'smsCode.require'                   => '请填写验证码!',
            ]
        );
        if ($validate->check($postData)) {
            $postData['user_id'] = $this->userId;
            $postData['type'] = 2;
            try {
                $this->__checkApproveSmsCode($postData);
                //地区转换
                $provincesId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'provinceid')) . '%')
                    ->where('area_deep', 1)
                    ->value('area_id') ?: 0;
                $cityId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'cityid')) . '%')
                    ->where('area_deep', 2)
                    ->where('area_parent_id', $provincesId)
                    ->value('area_id') ?: 0;
                $areaId = Db::name('area')
                    ->where('area_name', 'LIKE', '%' . Help::ignoreAreaSuffix(Arr::get($postData, 'areaid')) . '%')
                    ->where('area_deep', 3)
                    ->where('area_parent_id', $cityId)
                    ->value('area_id') ?: 0;
                $postData['provinceid'] = $provincesId;
                $postData['cityid'] = $cityId;
                $postData['areaid'] = $areaId;

                $result = (new UserService())->submitApproveCompany($postData);
                if ($result) {
                    $this->response();
                }
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    ApiConstant::API_ERROR_STR
                );
            } catch (\Exception $e){
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_ERROR,
            $validate->getError()
        );
    }


    /**
     * 验证用户申请认证成个人验证码
     * @param $postData
     *
     * @return bool
     * @throws \Exception
     */
    private function __checkApproveSmsCode($postData)
    {
        $sendSmsCode = session('smsCodeValue_' . $this->userId);
        $sendSmsTime = session('smsCodeTime_' . $this->userId);
        //10分钟有效期
        if ((time() - $sendSmsTime) < 600) {
            if (Arr::valueEq($postData, 'smsCode', $sendSmsCode)) {
                session('smsCodeValue_' . $this->userId, null);
                session('smsCodeTime_' . $this->userId, null);
                return true;
            }
            throw new \Exception('验证码错误！');
        }
        session('smsCodeValue_' . $this->userId, null);
        session('smsCodeTime_' . $this->userId, null);
        throw new \Exception('验证码有效期已过！');
    }


}
